package cm.config;

import cm.entity.ScheduleSettingDO;
import cm.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * @author: yxh
 * @Description: 配置
 * @Date: Created in 2022/12/14 17:54
 * @Modified By:
 */
@Component
public class ScheduleSetting implements SchedulingConfigurer {

    @Autowired
    private ScheduleService scheduleService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        List<ScheduleSettingDO> scheduleList = scheduleService.selectListByParam(10,1);
        for (ScheduleSettingDO s : scheduleList){
            scheduledTaskRegistrar.addTriggerTask(getRunnable(s), getTrigger(s));
        }
    }

    /**
     * 首字母转换
     * @param str
     * @return
     */
    public static String lowerFirstCase(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
    private Runnable getRunnable(ScheduleSettingDO scheduleSettingDO) {
        return new Runnable() {
            @Override
            public void run() {
                Class clazz;
                try {
                    clazz = Class.forName(scheduleSettingDO.getClassName());
                    String className = lowerFirstCase(clazz.getSimpleName());
                    Object bean = (Object) ApplicationContextHelper.getBean(className);
                    Method method = ReflectionUtils.findMethod(bean.getClass(), scheduleSettingDO.getMethod());
                    ReflectionUtils.invokeMethod(method, bean);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
    }
    private Trigger getTrigger(ScheduleSettingDO scheduleSettingDO){
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger trigger = new CronTrigger(scheduleSettingDO.getCron());
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };
    }
}
